(function(global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global = global || self, global.LucidityNoteApp = factory());
})(this, (function() {
    'use strict';

    function LucidityNoteApp() {
        var this$1 = this;
        if (!(this instanceof LucidityNoteApp)) { return new LucidityNoteApp() } 
    };

    /**
     * sf3Loader 加载器
     */
    const sf3Loader = {
        loader: window['vue3-sfc-loader'].loadModule,
        options: {
            moduleCache: {
                vue: Vue
            },
            async getFile(url) {
                const res = await fetch(url);
                if (!res.ok)
                    throw Object.assign(new Error(res.statusText + ' ' + url), {
                        res
                    });
                return {
                    getContentData: asBinary => asBinary ? res.arrayBuffer() : res.text(),
                }
            },
            addStyle(textContent) {
                const style = Object.assign(document.createElement('style'), {
                    textContent
                });
                const ref = document.head.getElementsByTagName('style')[0] || null;
                document.head.insertBefore(style, ref);
            },
        },
    };

    LucidityNoteApp.default = ()=>{}

    /**
     * 视图层常量定义
     */
    LucidityNoteApp.VIEWS = {
        app: '/ui/template/vue/lucidity.note.app.vue',
        header: '/ui/template/vue/lucidity.note.app.header.vue',
        aside: '/ui/template/vue/lucidity.note.app.aside.vue',
        main: '/ui/template/vue/lucidity.note.app.main.vue',
        footer: '/ui/template/vue/lucidity.note.app.footer.vue',

        editor: '/ui/template/vue/lucidity.note.app.main.editor.vue',
        overview: '/ui/template/vue/lucidity.note.app.main.overview.vue',
        // 笔记本信息组件
        notebook: '/ui/template/vue/lucidity.note.app.notebook.vue',
        // 用户设置
        settings: '/ui/template/vue/lucidity.note.app.settings.vue',
    };

    // LucidityNoteApp 的一些组件间的交互指令
    LucidityNoteApp.COMMANDS = {
        // aside 边栏加载笔记树指令
        loadTree: "load-notetree-command",
        // 点击文件树节点打开文件
        openFile: "open-click-file"
    }

    /**
     * Lucidity 组件异步加载
     * @param {string} path 组件路径
     * @returns 
     */
    LucidityNoteApp.defineAsyncComponent = (path) => {
        return Vue.defineAsyncComponent(() => sf3Loader.loader(path, sf3Loader.options));
    };

    LucidityNoteApp.refreshReource = () => {
        axios.get("/user/setting/resources", null)
        .then((response) => {
            var responseData = response.data.data;
            // 背景图片
            var bkUrl = responseData.bkImage
            document.body.style.background = `url("${bkUrl}") no-repeat center center`;
            // App主题
            var appTheme = document.createElement("link")
            appTheme.rel = "stylesheet"
            appTheme.href = `/assets/static/css/lucidity.note.${responseData.appTheme}.theme.v1.0.0.css`
            document.head.appendChild(appTheme)
            // Editor主题
            var editorTheme = document.createElement("link")
            editorTheme.rel = "stylesheet"
            editorTheme.href = `/assets/static/moudle/codemirror/theme/${responseData.editorTheme}.css`
            document.head.appendChild(editorTheme)

        });
    };

    LucidityNoteApp.changeJSScript = (id, url) => {
        document.getElementById(id).href = url;
    }

    /**
     * 页面初始化
     */
    LucidityNoteApp.init = () => {
        LucidityNoteApp.refreshReource();
        
        // 初始化 vue 实例和加载 vue 组件
        const app = Vue.createApp({
            components: {
                'lucnote-note-app': LucidityNoteApp.defineAsyncComponent(LucidityNoteApp.VIEWS.app),
            },

            setup() {
            }
        });

        // 添加 elementui-vue3 图标集
        for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
            app.component(key, component)
        }

        // 使用 elementui-vue3
        app.use(ElementPlus);
        app.mount("#app");
    };

    // 动态加载 JS 文件
    LucidityNoteApp.loadJS = (customeAttr, urls) => {
        return new Promise((resolve, reject) => {
            if (customeAttr === "deleteScript") {
                // 如果存在自定义属性名称等于deleteScript,那么先去删除上一次动态添加的标签在添加新的标签
                // let delScript = document.querySelector("script[data-callType='deleteScript']")
                let delScripts = document.querySelectorAll("script[data-callType='deleteScript']")
                if (delScripts && delScripts.length > 0) {
                    delScripts.forEach(element => {
                        document.head.removeChild(element)
                    })
                }
            }

            var times = 0;
            urls.forEach(element => {
                var script = document.createElement("script")
                script.type = "text/javascript"
                script.setAttribute("data-callType", customeAttr)
                script.src = element
                document.head.appendChild(script)

                // 只要出现一个加载失败的则终止加载
                script.onerror = () => {
                    reject();
                }

                // 只有当所有的文件全部加载完毕之后才能回调成功
                script.onload = () => {
                    times = times + 1;
                    if (times == urls.length) {
                        resolve();
                    }
                }
            });
        });
    }



    LucidityNoteApp.$mitt = mitt();

    return LucidityNoteApp;
}));

// (function(mod) {
//     if (typeof exports == "object" && typeof module == "object") // CommonJS
//       mod(require("/assets/static/javascript/lucidity.note.app.v1.0.0.js"));
//     else if (typeof define == "function" && define.amd) // AMD
//       define(["/assets/static/javascript/lucidity.note.app.v1.0.0.js"], mod);
//     else // Plain browser env
//       mod(LucidityNoteApp);
// }) (function(LucidityNoteApp) {
//     "use strict";

// })